<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发送get/post请求</title>
</head>
<body>
    <button id="btn1">发送get请求</button>
    <button id="btn2">发送post请求</button>
    <button id="btn3">歌曲</button>
    
    <!-- 接收响应数据 -->
    <div id="box1"></div>
    <ul id="box2"></ul>
    <ul id="box3"></ul>
    
    <!-- 使用axios库来处理HTTP请求 -->
     <script src="../js/axios.js"></script>
     <script>
        let btn1Ele = document.getElementById("btn1");
        let btn2Ele = document.getElementById("btn2");
        let box1Ele = document.getElementById("box1");
        let box2Ele = document.getElementById("box2");
        let btn3Ele = document.getElementById("btn3");
        let box3Ele = document.getElementById("box3");
        
  
        btn1Ele.addEventListener("click", async () => {
          // 发送get请求
          // axios请求结果返回的是promise(承诺)，承诺成功或者失败，
          // 获取其成功结果可在前面加个await等待其成功的结果，
          // await不能单独使用，要在其所属的函数前面加个async
          try {
          console.log('Sending GET request to /user');
          let { data } = await axios({
            method: "get",
            url: "http://127.0.0.1:4000/user",
          });
          console.log('Received response:', data);
          let { name, age } = data;
          box1Ele.innerText = `名字叫${name}，年龄${age}`;
        } catch (error) {
          console.error('Error fetching user data:', error);
        }
      });

  
      btn2Ele.addEventListener("click", async () => {
        try {
          console.log('Sending POST request to /fruit');
          let { data } = await axios({
            method: "post",
            url: "http://127.0.0.1:4000/fruit",
          });
          console.log('Received response:', data);
          let lis = "";
          data.forEach((item) => {
            lis += `<li>${item}</li>`;
          });
          box2Ele.innerHTML = lis;
        } catch (error) {
          console.error('Error fetching fruit data:', error);
        }
      });

        btn3Ele.addEventListener("click", async () => {
        try {
          console.log('Sending GET request to /songs');
          let { data } = await axios({
            method: "get",
            url: "http://127.0.0.1:4000/songs?id=2636746926", 
          });
          console.log('Received response:', data);

          // 处理响应数据
          if (data && data.id) {
            let { id, name, author } = data;
            box1Ele.innerText = `ID:${id}，歌名：${name}, 作者：${author}`;
          } else {
            box1Ele.innerText = '没有找到对应的歌曲';
          }
        } catch (error) {
          console.error('Error fetching song data:', error);
          box1Ele.innerText = '获取歌曲信息时出错';
        }
      });
          
        
      </script>
</body>
</html>